import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { PrimengTableHelper } from 'shared/helpers/PrimengTableHelper';
import { forEach as _forEach, remove as _remove } from 'lodash-es';
import { Table } from 'primeng/table';
import { Paginator } from 'primeng/paginator';
import {
    ContentConfig,
    ContentListConfigItem,
    IEntityDtoOfGuid,
    NewSortNumberWithMenuIdInput,
    Content2ServiceProxy
} from '@shared/service-proxies/service-proxies';
import { map as _map } from 'lodash-es';

import { AppLocalizationService } from '@app/shared/common/localization/app-localization.service';
import { finalize } from 'rxjs/operators';
import { AppNotifyService } from '@shared/utils/service/app-notify.service';
import { IGoRelatePageDto } from '@app/main/content/IContentComponent';
import { AppContent2Service } from '../app-content2.Service';
import { IContent2Component } from '../IContent2Component';
import { HtmlHelper } from '@shared/helpers/HtmlHelper';

@Component({
    selector: 'content2-list-tab',
    templateUrl: './content2-list.component.html'
})
export class content2ListComponent {
    @Input() primengTableHelper: PrimengTableHelper;

    @Input() permissionDic: { [key: string]: boolean };

    @Input() pageConfig: ContentConfig;

    @ViewChild('dataTable', { static: true }) dataTable: Table;
    @ViewChild('paginator', { static: true }) paginator: Paginator;


    @Output() getListData: EventEmitter<any> = new EventEmitter<any>();
    @Output() changeOrderFunc: EventEmitter<number> = new EventEmitter<number>();
    @Output() editModal: EventEmitter<any> = new EventEmitter<any>();
    @Output() goRelatePage: EventEmitter<IGoRelatePageDto> = new EventEmitter<IGoRelatePageDto>();

    selectedDatas: IEntityDtoOfGuid[] = [];

    get kind(){
        return this.controller.kind;
    }

    controller: IContent2Component; 

    get listConfig(): ContentListConfigItem[] {
        if (this.pageConfig) {
            return this.pageConfig.list;
        }

        return [];
    }


    constructor(
        private notify: AppNotifyService,
        private _localizationNewService: AppLocalizationService,
        private _contentServiceProxy: Content2ServiceProxy,
        private _contentService: AppContent2Service
    )
    {

    }

    getList($event) {
        this.getListData.emit($event);
    }

    getSelectedIds() {
        let ids = _map(this.selectedDatas, selectedMember => selectedMember.id);
        return Array.from(new Set(ids));
    }

    goRelate(record: { [key: string]: any; }, config: ContentListConfigItem) {
        this.goRelatePage.emit({
            id: record.id,
            relateDataCustomKey: config.relateDataKey,
            relateDataContentType: config.contentType,
            displayName: this._localizationNewService.l(config.displayName)
        });
    }

    changeOrder($event, item: { [key: string]: any; }) {
        let order = item.order;

        let regu = /^[1-9]\d*$/;
        if (!regu.test($event.target.value)) {
            $event.target.value = order;
            return;
        }

        var newOrder = parseInt($event.target.value);
        if (isNaN(newOrder)) {
            $event.target.value = order;
            return;
        } else if (newOrder !== order) {
            let isSuccess = false;
            this.primengTableHelper.isLoading = true;

            let input = new NewSortNumberWithMenuIdInput();
            input.id = item.id;
            input.newNumber = newOrder;
            input.menuId = item.menuId;
            input.relateId = item.relateId;

            this._contentServiceProxy.setNewOrderNumber(input)
                .pipe(finalize(() => {
                    this.primengTableHelper.isLoading = false;
                    if (!isSuccess) {
                        $event.target.value = order;
                    }
                }))
                .subscribe(result => {
                    isSuccess = true;
                    item.order = newOrder;
                    this.primengTableHelper.records.sort(function (a, b) {
                        return b.order - a.order;
                    });
                    this.notify.success(this._localizationNewService.l('OrderSuccessSuccessfully'));
                });
        }
    }

    getFormatTitle(entity: { [key: string]: any; }) {
        let title = HtmlHelper.truncate(entity.title, 35) + '&nbsp';
        if (entity.managementType === 0 /*管理*/ && entity.menuCount > 1) {
            if (entity.menuId.toString() === this.kind) {
                return "<i class=\"bi bi-share\"></i>  " + title;
            } else {
                return "<i class=\"bi bi-pencil-square\"></i>  " + title;
            }
        }
        else if (entity.managementType === 1 /*引用*/) {
            if (entity.menuId !== this.kind) {
                return "<i class=\"bi bi-link-45deg\"></i>  " + title; 
            }
        } else {
            return  title; 
        }
    }

    moveToAnotherMenu(entity: { [key: string]: any; }) {
        this._contentService.moveToAnotherMenu(this.controller, entity);
    }
    copyToOtherMenu (entity: { [key: string]: any; }) {
        this._contentService.copyToOtherMenu(this.controller, entity);
    }
    shareToOtherMenu (entity: { [key: string]: any; }) {
        this._contentService.shareToOtherMenu(this.controller, entity);
    }
    lookUpSharedList(entity: { [key: string]: any; }) {
        this._contentService.lookUpSharedList(this.controller, entity);
    }
    isSourceData(entity: { [key: string]: any; }){
        return entity.menuId == this.kind;
    }

    exDiyFunc(record, funcName:string, fieldName:string){
        this[funcName](record, fieldName);
    }
    getDiyFuncResult(record, funcName:string, fieldName:string){
        return this[funcName](record, fieldName);
    }

    getLabels(record, fieldName:string ) {
        let val = record[fieldName];
        if(val && val.length > 1){
            return val.substring(1, val.length -1).replace(/,/g, '、');
        }
        return val;
    }
}
